package com.ce.sys.conf.action;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import com.ce.framework.datamaintain.action.SearchAction;
import com.ce.framework.exception.AppException;
import com.ce.framework.util.StringUtil;
import com.ce.framework.util.Uuid;
import com.ce.sys.dict.dao.po.SysDictItem;
import com.ce.util.DbUtil;
import com.ce.util.PermissUtil;
import com.ce.util.TreeNode;

public class ConfigAction extends SearchAction{

	@SuppressWarnings({ "unchecked", "deprecation" })
	public String execute() throws Exception {
		String menuId = getParameter("menuId");
		if(StringUtil.isBlank(menuId)){
			HttpServletRequest request = getRequest();
			menuId = (String) request.getAttribute("menuId");
		}
		if(!PermissUtil.isHavePermissByMenuId("conf", menuId)){
			return writeHTML("您没有权限此模块的配置权限，请联系管理员!");
		}
		if("loadDict".equals(op)){
			return loadDict();
		}
		else if("saveDict".equals(op)){
			return saveDict();
		}
		else if("saveReg".equals(op)){
			return saveReg();
		}
		//取出菜单对参数的配置内容
		List<?> list = DbUtil.executeSqlQuery("select vc_id,vc_name,null,vc_memo from sys_t_menu t where t.vc_id=?",TreeNode.mapper4,new Object[]{menuId});
		if(list!=null&&list.size()>0){
			TreeNode node = (TreeNode) list.get(0);
			String memo = node.getVcUserData();
			memo = memo==null?"":memo;
			setAttribute("menuName", node.getVcName());
			String[] tmp = memo.split(";");
			String[] regs = tmp.length<1||tmp[0]==null?new String[0]:tmp[0].split(",");
			String[] dicts = tmp.length<2||tmp[1]==null?new String[0]:tmp[1].split(",");
			memo = getCookie("CONF_"+menuId);
			memo = memo==null?"":memo;
			tmp = memo.split(";");
			String[] regs2 = tmp.length<1||tmp[0]==null?new String[0]:tmp[0].split(",");
			String[] dicts2 = tmp.length<2||tmp[1]==null?new String[0]:tmp[1].split(",");
			List<TreeNode> rlist = (List<TreeNode>) DbUtil.executeSqlQuery("select vc_item,vc_name,vc_value,vc_note from sys_t_regedit where vc_name in ('"+
					StringUtil.join(regs, "','")+StringUtil.join(regs2, "','")+"')", TreeNode.mapper4);
			List<TreeNode> dlist = (List<TreeNode>) DbUtil.executeSqlQuery("select vc_id,vc_name,vc_org$id,vc_note from sys_t_dict$m where vc_name in ('"+
					StringUtil.join(dicts, "','")+StringUtil.join(dicts2, "','")+"')", TreeNode.mapper4);
			setAttribute("rlist", rlist);
			setAttribute("dlist", dlist);
			HashSet<String> hsreg = new HashSet<String>();
			HashSet<String> hsdict = new HashSet<String>();
			addToHashSet(regs,hsreg);
			addToHashSet(regs2,hsreg);
			addToHashSet(dicts,hsdict);
			addToHashSet(dicts2,hsdict);
			for(TreeNode n:rlist){
				hsreg.remove(n.getVcName());
			}
			for(TreeNode n:dlist){
				hsdict.remove(n.getVcName());
			}
			StringBuffer buff = new StringBuffer();
			if(hsreg.size()>0){
				buff.append("未配置的注册项：");
				for(String s:hsreg){
					buff.append(s).append(",");
				}
				buff.deleteCharAt(buff.length()-1);
			}
			if(hsdict.size()>0){
				buff.append(buff.length()>0?"<br/>":"").append("未配置的公共字典：");
				for(String s:hsdict){
					buff.append(s).append(",");
				}
				buff.deleteCharAt(buff.length()-1);
			}
			setAttribute("warn", buff.toString());
		}
		return SUCCESS;
	}
	private void addToHashSet(String[] ary,HashSet<String> hs){
		for(String s:ary){
			if(s!=null&&s.length()>0){
				hs.add(s);
			}
		}
	}

	private String saveReg() {
		String vcName = getParameter("vcName");
		String vcValue = getParameter("vcValue");
		int i=DbUtil.executeSqlUpdate("update sys_t_regedit set vc_value=? where vc_name=?",new Object[]{vcValue,vcName});
		if(i==0){
			return returnInfoForJS(false,"未找到要修改的注册项!");
		}
		return returnInfoForJS(true,"保存成功!");
	}

	private String saveDict() {
		String vcMId = getParameter("vcMId");
		String[] vcId = getParameterValues("vcId");
		String[] vcItemNumber = getParameterValues("vcItemNumber");
		String[] vcItemName = getParameterValues("vcItemName");
		String[] vcItemNote = getParameterValues("vcItemNote");
		String[] vcDelFlag = getParameterValues("vcDelFlag");
		String[] nseq = getParameterValues("nseq");
		List<SysDictItem> addlist = new ArrayList<SysDictItem>(),updatelist=new ArrayList<SysDictItem>();
		try {
			for(int i=0;i<vcId.length;i++){
				SysDictItem po = getDictItem(vcId[i]);
				if(po==null){
					if("1".equals(vcDelFlag[i])){//新增后被删除的内容不做保存
						continue;
					}
					po = new SysDictItem();
					po.setVcId(Uuid.getUuid());
					po.setVcMId(vcMId);
					po.setVcDelFlag(0);
					addlist.add(po);
				}
				else{
					updatelist.add(po);
				}
				po.setVcItemNumber(vcItemNumber[i]);
				po.setVcItemName(vcItemName[i]);
				po.setVcItemNote(vcItemNote[i]);
				po.setVcDelFlag("1".equals(vcDelFlag[i])?1:0);
				try {
					po.setNseq(Integer.parseInt(nseq[i]));
				} catch (Exception e) {
				}
			}
			baselogic.addPo(null, addlist);
			baselogic.updatePos(updatelist);
		} catch (Exception e) {
			e.printStackTrace();
			return returnInfoForJS(false, e.getMessage());
		}
		return returnInfoForJS(true,"保存成功!");
	}
	
	private SysDictItem getDictItem(String vcId){
		if(StringUtil.isBlank(vcId)){
			return null;
		}
		try {
			return (SysDictItem) baselogic.getPOByPk(SysDictItem.class.getName(), vcId);
		} catch (AppException e) {
			return null;
		}
	}

	private String loadDict() {
		String vcId = getParameter("vcId");
		List<?> list = DbUtil.executeHql("from SysDictItem po where po.vcDelFlag=0 and po.vcMId='"+vcId +"' order by po.nseq");
		setAttribute("vcMId", vcId);
		setAttribute("dictlist", list);
		return "dictitem";
	}

}
